﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;//for list
using System.IO;
using GMS.Model;
using GMS.BLL;
//using GMS.Utils.ServiceContext;
//using GMS.BLL.Approval;
using GMS.Utils;
using GMS.Web.CommonPage;
using GMS.Web.CommonPage.BasePage;

public partial class UserManagerDetails : CommonDetailBase
{
    HtmlProvider MC = new HtmlProvider();
    private ComOperate CDO = new ComOperate();
    private ColumnsManager ClsManager = new ColumnsManager();
    private TabColumnsBLL tabColumnBll = new TabColumnsBLL();
    //GatherHotScheme ghs = new GatherHotScheme();
    //DBAndBizTableConverter BizTab = new DBAndBizTableConverter();
    ComFunctions CFs = new ComFunctions();
    public int itabCols = 0;
    public string tabDBCode = "";
    //RuleManager ruleManager = new RuleManager();
    //审批为空设置
    Dictionary<string, EnumHelper.E_EmptyType> approveEmptyType = new Dictionary<string, EnumHelper.E_EmptyType>();
    bool needApproval = false;
    enum EditOrAdd
    {
        Add,
        Edit
    }

    FilesDB template = new FilesDB(); //用于UploadFiles初始化
    private bool isLoginUserDetail = false; //true表示是查看当前用户信息，false表示用户管理中的详情


    protected void Page_Load(object sender, EventArgs e)
    {
        if (isRestored || !IsPostBack)
        {
            string skeys = string.Empty;
            try
            {
                if (Request.QueryString["cdtion"] != null)//编辑
                {
                    skeys = Request.QueryString["cdtion"].ToString();

                    //没有传过来类似ID-3格式的数据，表示查看登录用户自己信息
                    if (skeys.Equals("") && Request.QueryString["tablecode"].ToUpper().Equals("TAB_USER"))
                    {
                        skeys = GetLoginUserIndexId();
                        isLoginUserDetail = true;
                    }
                    this.submitType.Value = "" + (int)EditOrAdd.Edit;
                    this.btnSave.Visible = false;
                    SetSessionForBack(Request.QueryString["tablecode"].ToUpper(), Request.QueryString["cdtion"], Request.Params["editable"]);
                    DisplayDetails(skeys);
                }
                else //新建
                {
                    this.submitType.Value = "" + (int)EditOrAdd.Add;
                    //this.btnSave.Visible = true;
                    //this.btnMod.Visible = true;
                    DisplayNewDetails();
                }

                isRestored = false;
                this.SPANTitle.InnerText = CDO.Table.TABNAME + "——详细信息";
            }
            catch (Exception ex)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');history.back();", true);
                return;
            }
        }
        
    }
    //用于设置session，用于图片上传后返回的刷新。
    private void SetSessionForBack(string tablecode, string cdtion, string editable)
    { 
           if (Session["cdtionforback"]!=null)
          {
              Session["cdtionforback"] = cdtion;
          }
          else
          {
              Session.Add("cdtionforback", cdtion);
          }
          if (Session["tablecodeforback"] != null)
          {
              Session["tablecodeforback"] = tablecode;
          }
          else
          {
              Session.Add("tablecodeforback", tablecode);
          }
           if (Session["editableforback"]!=null)
          {
              Session["editableforback"] = editable;
          }
          else
          {
              Session.Add("editableforback", editable);
          }
    }
    #region 编辑显示
    /// <summary>
    /// 编辑页面显示
    /// </summary>
    /// <param name="skeys">传递的页面参数,包含主键列名和值</param>
    public void DisplayDetails(string skeys)
    {
        int iColumn = 2;//table总列数
        int iNum = iColumn;//控制一行二列
        string cityCode = string.Empty;

        //页面加载完要执行的JavaScript,控制关联下拉框的选中
        System.Text.StringBuilder scriptBuilder = new System.Text.StringBuilder();

        //查询条件
        Dictionary<string, string> values = new Dictionary<string, string>();
        //输出的html语句
        System.Text.StringBuilder detailHtmlBudiler = new System.Text.StringBuilder();
        //判断整行是否只读
        //通过获取权限判断是否可修改
        //bool allReadOnly = true;
        bool allReadOnly = false;
        //if (Request.Params["editable"] != null)
        //{
        //    if (Request.Params["editable"].Equals("uneditable"))
        //    {
        //        allReadOnly = true;
        //    }
        //}
        if(Session["TabSysID"] != null)
            if (!RoleModuleRightOper.HasUpdateRight((GMS.Model.User)Session["_User"],(int)Session["TabSysID"]))
                allReadOnly = true;


        //去掉"-"后的表名
        //tabDBCode = BizTab.TableCodeBiz2DB(tableCode);
        //分析主键与值,组织查询条件       
        if (string.IsNullOrEmpty(skeys))
            return;

        string[] arr = skeys.Split(';');
        for (int i = 0; i < arr.Length; i++)
        {
            values.Add(arr[i].Split('-')[0], arr[i].Split('-')[1]);
        }
        //用表名初始化ComOperate,结合ID值获取数据
        CDO.Init(tableCode.ToUpper());
        DataTable dtDetails = CDO.GetDetailBySearchDict(values);
        if (tableCode.IndexOf("-") >= 0)
        {
            //取汇总数据或分类数据
            //dtDetails = BizTab.TableColDB2Biz(tableCode, dtDetails);
        }

        ////判断是否审批表,是则取出审批为空类型限制,table为直接可能含有-的表的实例,CDO.Table为不含有-的表的实例,审批判断应保留-
        //if (CDO.Table.ISAPPROVAL == (int)EnumHelper.E_YesOrNo.YES)
        //{
        //    approveEmptyType = ruleManager.findEmptyRuleByTable(tableCode);
        //}
        Dictionary<string, GMS.Model.TabColumns> columns = CDO.TabColDict;
        //不可修改日期判断
        //allReadOnly = CheckCreateDTReadOnly(dtDetails);
        //if (!allReadOnly)
        //{
        //    //分公司修改权限判断
        //    allReadOnly = CheckCityReadOnly(columns, dtDetails);
        //}
        btnSubmit.Disabled = allReadOnly;

        foreach (TabColumns column in columns.Values)
        {
            if (!dtDetails.Columns.Contains(column.COLCODE))
                continue;
            int iType = column.COLTYPE;
            string ForgineCol = column.FOREIGNCOL;
            string ForgineColName = column.FOREIGNSHOWCOL;
            string colCode = column.COLCODE;
            //下拉框下拉列表
            DataTable dtSelected = new DataTable();
            //下拉框关联列表
            DataSet relateDS;

            string sFatherValue = string.Empty;
            relateDS = new DataSet();

            if (iType == (int)EnumHelper.E_ColDataType.COL_AUTOID)
            {
                template.BELONGID = dtDetails.Rows[0][colCode].ToString();
            }
            if (column.COLDETAILSHOWED == null || column.COLDETAILSHOWED == (int)EnumHelper.E_YesOrNo.No/* || column.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_NOMODIFIED*/)
                continue;
            #region output tr
            if (iNum == iColumn)
            {
                detailHtmlBudiler.Append("<tr>");
                detailHtmlBudiler.Append("\r\n");
            }
            else if (iNum <= 0)
            {
                iNum = iColumn;
                detailHtmlBudiler.Append("</tr>");
                detailHtmlBudiler.Append("\r\n");
            }
            --iNum;
            #endregion

            //列是否允许编辑
            bool readOnly = true;//IsReadOnly();
            if (!allReadOnly)
                readOnly = CheckColReadOnly(column);

            if (!string.IsNullOrEmpty(column.FOREIGNTAB))
            {
                iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_DDL;
                if (CDO.Relation.ContainsKey(column.FOREIGNTAB + "," + colCode))
                {
                    string dtSelectSql = CDO.Relation[column.FOREIGNTAB + "," + colCode];
                    if (column.FOREIGNTAB.ToUpper() == "TAB_SYSPARAMETERS" || !readOnly)
                        //dtSelected = Maticsoft.DBUtility.DbHelperSQL.DataTable(dtSelectSql);在这里直接调用DbHelper是不合适的。应该是：
                        dtSelected = CDO.CdoDb.DataTable(dtSelectSql);
                    else //支持access，所以去掉''
                        dtSelected = CDO.CdoDb.DataTable("select * from (" + dtSelectSql + ") where " + ForgineCol + "=" + dtDetails.Rows[0][colCode].ToString() + "");
                       //dtSelected = CDO.CdoDb.DataTable("select * from (" + dtSelectSql + ") where " + ForgineCol + "='" + dtDetails.Rows[0][colCode].ToString() + "'");
                        //dtSelected = Maticsoft.DBUtility.DbHelperSQL.DataTable("select * from (" + dtSelectSql + ") where " + ForgineCol + "='" + dtDetails.Rows[0][colCode].ToString() + "'");
                    dtSelected.TableName = colCode;
                    relateDS.Tables.Add(dtSelected);

                    if (column.FOREIGNTAB.ToUpper() == "TAB_CITY")
                        cityCode = dtDetails.Rows[0][colCode].ToString();
                }

                DataTable tempDT = new DataTable();
                DataTable dt;
                //取关联DataTable
                foreach (KeyValuePair<string, string> pair in CDO.Relation)
                {
                    if (pair.Key.ToUpper().StartsWith(column.FOREIGNTAB.ToUpper() + "," + colCode.ToUpper() + "-"))  //父级获得所有父级子级数据
                    {

                        dt = CDO.CdoDb.DataTable(pair.Value);
                        tempDT = dt.Copy();
                        tempDT.TableName = pair.Key.Substring(pair.Key.IndexOf(',') + 1);
                        relateDS.Tables.Add(tempDT);
                        iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                        continue;
                    }
                    if (pair.Key.ToUpper().Contains("-" + colCode.ToUpper() + "-"))
                    {
                        relateDS = null;
                        iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                        break;
                    }

                }
                if (relateDS != null && relateDS.Tables.Count > 1)
                    detailHtmlBudiler.Append(MC.GetSysObjScripts(relateDS, column.FOREIGNTAB));
            }

            //审核状态字段处理
            string colValue = dtDetails.Rows[0][colCode].ToString();
            //if (ApprovalHelper.IsBatchStatusCol(tableCode, colCode))
            //{
            //    colValue = ApprovalHelper.ConvertBatchNo2Name(colValue);
            //}
            if (column.FATHERCURRENTCOLNAME != "")
            {
                sFatherValue = dtDetails.Rows[0][column.FATHERCURRENTCOLNAME].ToString();
                scriptBuilder.AppendLine("SysDynamicOptions(document.getElementById('Cls" + column.FATHERCURRENTCOLNAME.ToUpper() + "'));");
                if (!string.IsNullOrEmpty(colValue))
                {
                    scriptBuilder.AppendLine("var slt_" + colCode + "=document.getElementById('Cls" + colCode.ToUpper() + "');");
                    scriptBuilder.AppendLine("if(slt_" + colCode + "!=null && typeof(slt_" + colCode + ")!='undefined'){");
                    scriptBuilder.AppendLine("var optslen_" + colCode + "=slt_" + colCode + ".options.length;");
                    scriptBuilder.AppendLine("for(var i=0;i<optslen_" + colCode + ";i++)");
                    scriptBuilder.AppendLine("{if(slt_" + colCode + ".options[i].value=='" + colValue + "'){slt_" + colCode + ".options[i].selected=true;break;}}}");
                }
            }
            else
                sFatherValue = null;

            int? maxlength = column.MAXLENGTH;

            //允许为空
            bool nullable = false;
            if (column.COLNULLABLE == (int)EnumHelper.E_YesOrNo.YES)
                nullable = true;


            if (column.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_PASSWORD)//密码
            {                
                MD5 md5 = new MD5();
                if(!string.IsNullOrEmpty(colValue))
                    colValue = md5.DecryptString(colValue, dtDetails.Rows[0]["PWDKEY"].ToString());
                detailHtmlBudiler.Append(MC.DisplayPasswordDetails(0, colCode, column.COLNAME, colValue, maxlength, nullable,readOnly));
            }
            else //其他的
                detailHtmlBudiler.Append(MC.DisplayDetails(0, iType, readOnly, colCode,
                    column.COLNAME, colValue, dtSelected, sFatherValue, ForgineCol, ForgineColName, maxlength, nullable));

            //必填项
            if (!nullable || (approveEmptyType != null && approveEmptyType.ContainsKey(colCode.ToUpper()) && approveEmptyType[colCode.ToUpper()] == EnumHelper.E_EmptyType.CanNotBeNull))
            {
                detailHtmlBudiler.Length -= 5;
                if (readOnly || allReadOnly) //只读的时候没必要显示*
                    detailHtmlBudiler.Append("<font color='Red'></font>");//这行必须要，否则就变成多列了
                else
                    detailHtmlBudiler.Append(MC.GetEmptyTypeXNotNull());
                detailHtmlBudiler.Append("</td>");
                detailHtmlBudiler.Append("\r\n");
            }
            else if (approveEmptyType != null && approveEmptyType.ContainsKey(colCode.ToUpper()) && approveEmptyType[colCode.ToUpper()] == EnumHelper.E_EmptyType.NullAndSubmit)
            //建议项写项
            {
                detailHtmlBudiler.Length -= 5;
                detailHtmlBudiler.Append(MC.GetEmptyTypeXNullAndSubmit());
                detailHtmlBudiler.Append("</td>");
                detailHtmlBudiler.Append("\r\n");
            }
        }
        tbDetails.InnerHtml = detailHtmlBudiler.ToString();
        //如果为tab_overline表，需要设置定位按钮
        if (tableCode.ToUpper().Equals("TAB_OVERLINE") && !(dtDetails.Rows[0]["WKT"].ToString().Equals("")))
        {
            addbutton.InnerHtml = "<input type=\"button\" class=\"buttonface\" value=\"定位到地图\" onclick='javascript:parent.zoomTo(\"" + dtDetails.Rows[0]["WKT"].ToString() + "\")'/>";
            addbutton.Visible = true;
        }
        if (dtDetails.Columns.Contains("LONGITUDE") && dtDetails.Columns.Contains("LATITUDE"))
        {
            addbutton.InnerHtml = "<input type=\"button\" class=\"buttonface\" value=\"定位到地图\" onclick='javascript:parent.centerAt(" + dtDetails.Rows[0]["LONGITUDE"].ToString() + "," + dtDetails.Rows[0]["LATITUDE"].ToString() + ")'/>";
            addbutton.Visible = true;
        }
        //上传照片控件显示
        if (Int32.Parse(CDO.Table.ISUPLOADPHOTO) == (int)EnumHelper.E_YesOrNo.YES)
        {
            this.upFiles.Visible = true;

            //需要设置如下字段：BELONGTABLE, BELONGID, CITYCODE, DEPT, FILETYPE, CREATOR
            template.BELONGTABLE = CDO.Table.TABCODE;
            //template.BELONGID 前面已经设置
            //template.CITYCODE = (cityCode == string.Empty) ? user.COMPANY : cityCode;
            //template.DEPT = user.DEPARTMENT;
            template.FILETYPE = CDO.Table.TABNAME + "_照片";
            template.CREATOR = userAccount;

            upFiles.Initialize(template, true, false);
            upFiles.Refresh();
        }
        else
        this.upFiles.Visible = false;

        ClientScript.RegisterStartupScript(this.GetType(), "", scriptBuilder.ToString(), true);
    }
    #endregion

    bool CheckColReadOnly(TabColumns col)
    {
        if (col.COLTYPE == (int)EnumHelper.E_ColDataType.COL_AUTOID
            || ((col.COLOPRFEATURE != null) && (col.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_NOMODIFIED 
                 || col.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_SYSDOIT))
            || ConstantHelper.C_GENERALPAGE_AUTO_ADD.IndexOf(col.COLCODE) != -1)
            return true;

        //用户修改自己信息的时候，除非有编辑权限，否则自己不能修改角色、状态信息
        //但是此处写死不好，万一数据库字段名改了，就无效了，做成可配置的好
        if (col.COLCODE.ToUpper().Equals("TABUSERROLECODE") || col.COLCODE.ToUpper().Equals("STATUS"))
        {
            if (isLoginUserDetail) //表示是查看当前用户信息
                return true;
            else
                return false;
        }
        return false;
    }

    //用分公司判断整行记录（所有字段）是否只读
    bool CheckCityReadOnly(Dictionary<string, GMS.Model.TabColumns> titles, DataTable dtDetails)
    {
        //CheckSession();
        //bool hasCityCol = false;
        //foreach (TabColumns col in titles.Values)
        //    if (col.FOREIGNTAB.ToUpper().Equals("TAB_CITY"))
        //    {
        //        hasCityCol = true;
        //        string strInput = dtDetails.Rows[0][col.COLCODE].ToString();
        //        if (OP.CityUpdateRight.IndexOf("'" + strInput + "'") != -1)
        //            return false;
        //        else
        //            return true;
        //    }
        //if (!hasCityCol)
        //    return false;
        return false;
    }

    //判断创建日期早于不可修改日期,这行记录字段只读
    bool CheckCreateDTReadOnly(DataTable dtDetails)
    {
        bool readOnly = false;
        //if (CDO.Table.NoUpdateDate != null && !string.IsNullOrEmpty(dtDetails.Rows[0]["CREATEDT"].ToString()))
        //    if (CDO.Table.NoUpdateDate > (DateTime)dtDetails.Rows[0]["CREATEDT"])
        //        readOnly = true;
        return readOnly;
    }

    #region 新建显示
    public void DisplayNewDetails()
    {
        int iColumn = 2;//table总列数
        int iNum = iColumn;

        //页面加载完要执行的JavaScript,控制关联下拉框的选中
        System.Text.StringBuilder scriptBuilder = new System.Text.StringBuilder();

        //查询条件
        Dictionary<string, string> values = new Dictionary<string, string>();
        //输出的html语句
        System.Text.StringBuilder detailHtmlBudiler = new System.Text.StringBuilder();
        //判断整行是否只读
        bool allReadOnly = false;

        //去掉"-"后的表名
        //tabDBCode = BizTab.TableCodeBiz2DB(tableCode);

        //用表名初始化ComOperate,结合ID值获取数据
        CDO.Init(tableCode.ToUpper());
        CDO.SetTabColAndRelationForDetails(tableCode, null);

        //判断是否审批表,是则取出审批为空类型限制,table为直接可能含有-的表的实例,CDO.Table为不含有-的表的实例,审批判断应保留-
        //if (CDO.Table.ISAPPROVAL == (int)EnumHelper.E_YesOrNo.YES)
        //{
        //    approveEmptyType = ruleManager.findEmptyRuleByTable(tableCode);
        //}
        Dictionary<string, GMS.Model.TabColumns> columns = CDO.TabColDict;

        foreach (TabColumns column in columns.Values)
        {
            if (column.COLDETAILSHOWED == null || column.COLDETAILSHOWED == (int)EnumHelper.E_YesOrNo.No || column.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_NOMODIFIED)
                continue;
            int iType = column.COLTYPE;
            string ForgineCol = column.FOREIGNCOL;
            string ForgineColName = column.FOREIGNSHOWCOL;
            string colCode = column.COLCODE;
            //下拉框下拉列表
            DataTable dtSelected = new DataTable();
            //下拉框关联列表
            DataSet relateDS = new DataSet();

            string sFatherValue = string.Empty;

            #region output tr
            if (iNum == iColumn)
            {
                detailHtmlBudiler.Append("<tr>");
                detailHtmlBudiler.Append("\r\n");
            }
            else if (iNum <= 0)
            {
                iNum = iColumn;
                detailHtmlBudiler.Append("</tr>");
                detailHtmlBudiler.Append("\r\n");
            }
            --iNum;
            #endregion

            //列是否允许编辑
            bool readOnly = CheckColReadOnly(column);

            if (!string.IsNullOrEmpty(column.FOREIGNTAB))
            {
                iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_DDL;
                if (CDO.Relation.ContainsKey(column.FOREIGNTAB + "," + colCode))
                {
                    string dtSelectSql = CDO.Relation[column.FOREIGNTAB + "," + colCode];
                    dtSelected = CDO.CdoDb.DataTable(dtSelectSql);
                    dtSelected.TableName = colCode;
                    relateDS.Tables.Add(dtSelected);
                }

                DataTable tempDT = new DataTable();
                DataTable dt;
                //取关联DataTable
                foreach (KeyValuePair<string, string> pair in CDO.Relation)
                {
                    if (pair.Key.ToUpper().StartsWith(column.FOREIGNTAB.ToUpper() + "," + colCode.ToUpper() + "-"))  //父级获得所有父级子级数据
                    {

                        dt = CDO.CdoDb.DataTable(pair.Value);
                        tempDT = dt.Copy();
                        tempDT.TableName = pair.Key.Substring(pair.Key.IndexOf(',') + 1);
                        relateDS.Tables.Add(tempDT);
                        iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                        continue;
                    }
                    if (pair.Key.ToUpper().Contains("-" + colCode.ToUpper() + "-"))
                    {
                        relateDS = null;
                        iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                        break;
                    }

                }
                if (relateDS != null && relateDS.Tables.Count > 1)
                    detailHtmlBudiler.Append(MC.GetSysObjScripts(relateDS, column.FOREIGNTAB));
            }

            if (column.FATHERCURRENTCOLNAME != "")
            {
                scriptBuilder.AppendLine("SysDynamicOptions(document.getElementById('Cls" + column.FATHERCURRENTCOLNAME.ToUpper() + "'));");
            }
            else
                sFatherValue = null;

            int? maxlength = column.MAXLENGTH;

            //允许为空
            bool nullable = false;
            if (column.COLNULLABLE == (int)EnumHelper.E_YesOrNo.YES)
                nullable = true;

            if (column.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_PASSWORD)//密码               
                detailHtmlBudiler.Append(MC.DisplayPasswordDetails(0, colCode, column.COLNAME, "", maxlength, nullable,false));            
            else //其他的
                detailHtmlBudiler.Append(MC.DisplayDetails(0, iType, readOnly, colCode,
                    column.COLNAME, "", dtSelected, sFatherValue, ForgineCol, ForgineColName, maxlength, nullable));

            //必填项
            if (!nullable || (approveEmptyType != null && approveEmptyType.ContainsKey(colCode.ToUpper()) && approveEmptyType[colCode.ToUpper()] == EnumHelper.E_EmptyType.CanNotBeNull))
            {
                detailHtmlBudiler.Length -= 5;
                detailHtmlBudiler.Append(MC.GetEmptyTypeXNotNull());
                detailHtmlBudiler.Append("</td>");
                detailHtmlBudiler.Append("\r\n");
            }
            else if (approveEmptyType != null && approveEmptyType.ContainsKey(colCode.ToUpper()) && approveEmptyType[colCode.ToUpper()] == EnumHelper.E_EmptyType.NullAndSubmit)
            //建议项写项
            {
                detailHtmlBudiler.Length -= 5;
                detailHtmlBudiler.Append(MC.GetEmptyTypeXNullAndSubmit());
                detailHtmlBudiler.Append("</td>");
                detailHtmlBudiler.Append("\r\n");
            }
        }
        tbDetails.InnerHtml = detailHtmlBudiler.ToString();
        ClientScript.RegisterStartupScript(this.GetType(), "", scriptBuilder.ToString(), true);

        if (Int32.Parse(CDO.Table.ISUPLOADPHOTO) == (int)EnumHelper.E_YesOrNo.YES)
        {
            this.upFiles.Visible = true;


            //需要设置如下字段：BELONGTABLE, BELONGID, CITYCODE, DEPT, FILETYPE, CREATOR
            template.BELONGTABLE = CDO.Table.TABCODE;
            //新增记录，此时还不知道记录的AUTOID
            //template.BELONGID="" 
            //此时不用设置，整体提交时在保存前设置
            //template.CITYCODE = "";
            //template.DEPT = user.DEPARTMENT;
            template.FILETYPE = CDO.Table.TABNAME + "_照片";
            template.CREATOR = userAccount;

            upFiles.Initialize(template, true, true);
            upFiles.Refresh();
        }
        else
            this.upFiles.Visible = false;
    }
    #endregion

    #region 新建或修改提交
    public void BtnSubmitDetails(object sender, EventArgs e)
    {

        CheckSession();
        string type = Request.Form["submitType"];
        string rtnMsg = string.Empty;
        try
        {
            if (type == null)
            {
                throw new ArgumentException("缺少必要参数!");
                return;
            }
            SaveData(type);
        }
        catch (ArgumentException ae)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('" + comUse.SafeAlertMsg(ae.Message) + "');history.back();", true);
            return;
        }
        catch (Exception ex)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');history.back();", true);
            return;
        }
        if (tableState != null)
        {
            tableState = null;
            setGlobalState(null);
        }
        txtQueryData.Text = "";

        //注意：用下面注释的2行，会导致提交成功后，页面看不到原来刚修改的内容。        
        //Response.Write("<script>alert('保存成功！');</script>");
        //Server.Transfer(Request.Url.AbsolutePath);
        //换成下面一行：
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('保存成功！');history.back();", true);
    }

    private void SaveData(string type)
    {
        string sMesg = string.Empty;
        string skeys = string.Empty;
        string strCityCode = string.Empty;
        Dictionary<string, string> values = new Dictionary<string, string>();//<列名,值>,用于构造更新或插入SQL语句
        Dictionary<string, string> oldKey = null;

        //初始化表信息与表字段信息
        CDO.Init(tableCode);
        CDO.SetTabColAndRelationForDetails(tableCode, /*OP.CitySelectRight*/null);

        Dictionary<string, TabColumns> columns = CDO.TabColDict;
        //tabDBCode = BizTab.TableCodeBiz2DB(tableCode);

        //编辑时,取得ID值
        if (Request.QueryString["cdtion"] != null)//编辑
        {
            skeys = Request.QueryString["cdtion"].ToString();

            //表示用户查看自己的信息
            if (skeys.Equals("") && Request.QueryString["tablecode"].ToUpper().Equals("TAB_USER"))
                skeys = GetLoginUserIndexId();

            string[] arr = skeys.Split(';');
            for (int i = 0; i < arr.Length; i++)
            {
                values.Add(arr[i].Split('-')[0].ToUpper(), arr[i].Split('-')[1]);
            }
        }
        txtQueryData.Text = "";                

        bool hasCityCol = false;
        bool bInsert = false;
        bool bUpdate = false;
        foreach (TabColumns column in columns.Values)
        {
            int iType = column.COLTYPE;
            bInsert = false;
            bUpdate = false;
            string upColcode = column.COLCODE.ToUpper();

            //自增或不允许修改,编辑时ID在前面已获取
            if ((column.COLISKEY == (int)EnumHelper.E_ColIsKey.COL_SEQKEY)
                || (column.COLOPRFEATURE == ((int)EnumHelper.E_ColOprFeature.COL_NOMODIFIED))
                || column.COLDETAILSHOWED == (int)EnumHelper.E_YesOrNo.No)
                continue;

            string strInput = Request.Form["Cls" + column.COLCODE];
            txtQueryData.Text += "Cls" + column.COLCODE + "=" + strInput + ";";
            if (!string.IsNullOrEmpty(strInput))
                strInput = CFs.BizToDbData(strInput);


            if (column.COLNULLABLE == (int)EnumHelper.E_YesOrNo.No)
            {
                if (string.IsNullOrEmpty(strInput))
                {
                    if (iType != (int)EnumHelper.E_ColDataType.COL_AUTOID//非自增字段
                        && !((column.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_NOMODIFIED)//非不允许修改字段
                            || (ConstantHelper.C_GENERALPAGE_AUTO_ADD.IndexOf(column.COLCODE.ToUpper()) != -1)))//非自动填写字段
                    {
                        throw new ArgumentException(column.COLNAME + "不能为空！");
                    }
                }
                else //当为密码的时候，输入是空，但是strInput不为空，是","
                {
                    if (column.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_PASSWORD)
                    {
                        //strInput中的值是："密码,密码" 格式，先比较是否相同，再只取前面一个。 
                        string[] str = strInput.Split(',');
                        if (str[0].Equals("") || str[1].Equals(""))
                            throw new ArgumentException(column.COLNAME + "不能为空！");
                    }
                }
            }

            //当值是空时,判断是否允许为空
            if (string.IsNullOrEmpty(strInput))
            {
                if (column.COLNULLABLE == (int)EnumHelper.E_YesOrNo.No//不允许为空
                && iType != (int)EnumHelper.E_ColDataType.COL_AUTOID//非自增字段
                && !((column.COLOPRFEATURE == (int)EnumHelper.E_ColOprFeature.COL_NOMODIFIED)//非不允许修改字段
                    || (ConstantHelper.C_GENERALPAGE_AUTO_ADD.IndexOf(column.COLCODE.ToUpper()) != -1)))//非自动填写字段
                {
                    throw new ArgumentException(column.COLNAME + "不能为空！");
                }
               
            }

            if (type == "" + (int)EditOrAdd.Edit)//update
            {
                if (!values.ContainsKey(upColcode))
                {
                    if (!string.IsNullOrEmpty(strInput))
                    {
                        if (column.COLOPRFEATURE != ((int)EnumHelper.E_ColOprFeature.COL_PASSWORD))//普通值
                            values.Add(upColcode, strInput.ToString());
                        else//密码需要特殊处理
                        {
                            //strInput中的值是："密码,密码" 格式，先比较是否相同，再只取前面一个。 
                            string[] str = strInput.Split(',');
                            if (str[0].Equals(str[1]))
                            {
                                MD5 md5 = new MD5();
                                string pwdKey = md5.GenerateKey();                               
                                values.Add(upColcode, md5.EncryptString(str[0], pwdKey).ToString());
                                if(values.ContainsKey("PwdKey")) //已经包含了，更新
                                    values["PwdKey"] = pwdKey;
                                else //没有包含，添加
                                    values.Add("PwdKey", pwdKey);
                            }
                            else //密码不一样
                                throw new ArgumentException("密码不一样，请重新输入！");
                        }                            
                    }
                    else
                        //当为空的时候，要参与组装update语句               
                        values.Add(upColcode, null);
                }
                else
                {
                    //修改主键的情况，因为主键肯定已经在values里面了，所以只要更新一下值
                    if (!values[upColcode].Equals(strInput.ToString())) //改了主键
                    {
                        if (oldKey == null)
                            oldKey = new Dictionary<string, string>();
                        oldKey.Add(upColcode, values[upColcode].ToString());
                    }
                    values[upColcode] = strInput.ToString();
                }
            }
            else //insert
            {
                if (!string.IsNullOrEmpty(strInput))
                {
                    if (column.COLOPRFEATURE != ((int)EnumHelper.E_ColOprFeature.COL_PASSWORD))//普通值
                    {
                        if (!values.ContainsKey(upColcode))
                            values.Add(upColcode, strInput.ToString());
                        //当为空的时候，不参与组装insert语句 
                    }
                    else//密码
                    {
                        //strInput中的值是："密码,密码" 格式，先比较是否相同，再只取前面一个。 
                        string[] str = strInput.Split(',');
                        if (str[0].Equals(str[1]))
                        {
                            MD5 md5 = new MD5();
                            string pwdKey = md5.GenerateKey();
                            values.Add(upColcode, md5.EncryptString(str[0], pwdKey).ToString());
                            if (values.ContainsKey("PwdKey")) //已经包含了，更新
                                values["PwdKey"] = pwdKey;
                            else //没有包含，添加
                                values.Add("PwdKey", pwdKey);
                        }
                        else //密码不一样
                            throw new ArgumentException("密码不一样，请重新输入！");
                    }
                }
            }
        }

        if (tableCode.ToUpper().IndexOf("-") >= 0)
        {
            tabDBCode = tableCode.Substring(0, tableCode.IndexOf('-')).ToUpper();
            //values = BizTab.TableColBiz2DB(tableCode, values);
        }
        else
        {
            tabDBCode = tableCode;
        }

        if ((type.ToString() == "" + (int)EditOrAdd.Edit))
        {
            //下面2项自动增加,因为update时所有字段都在values里面
            if (values.ContainsKey("UPDATOR"))
                values["UPDATOR"] = userAccount;
            if (values.ContainsKey("UPDATEDT"))
                values["UPDATEDT"] = System.DateTime.Now.ToString();
            CDO.DetailUpdate(tabDBCode, values, oldKey);
            //upFiles.LoadFilesToDB(upFiles.file.AUTOID, tableCode, strCityCode);
        }
        else
        {
            if (values.Count == 0)
            {
                throw new ArgumentException("请输入数据！");
            }
            //下面2项自动增加，必须从dtTitles里面取，values里面没有
            foreach (TabColumns column in columns.Values)
            {
                if (column.COLCODE.ToUpper().Equals("SUBMITER"))
                    values["SUBMITER"] = userAccount;
                if (column.COLCODE.ToUpper().Equals("SUBMITTIME"))
                    values["SUBMITTIME"] = System.DateTime.Now.ToString();

                if (column.COLCODE.ToUpper().Equals("CREATOR"))
                    values["CREATOR"] = userAccount;
                if (column.COLCODE.ToUpper().Equals("CREATEDT"))
                    values["CREATEDT"] = System.DateTime.Now.ToString();
            }

            CDO.DetailInsert(tabDBCode, tableCode, values, false);


            #region 将UploadFiles控件中的文件保存
            //之前应该已经在DisplayDetails()和DisplayNewDetails()中调用upFiles.Initialize()
            //string citycode = string.Empty;
            //if (Request.QueryString["cdtion"] != null)//编辑 
            //{
            //    citycode = values["CITYCODE"];
            //}
            //else
            //{
            //    citycode = Request.Form["ClsCITYCODE"];
            //    if (string.IsNullOrEmpty(citycode))
            //    {
            //        citycode = user.COMPANY;
            //    }
            //    //插入时已经设置
            //    upFiles.FilesDBModelTemplate.BELONGID = template.BELONGID;
            //}
            //upFiles.SaveFiles(citycode);
            //upFiles.Refresh();
            #endregion
        }
    }

    #endregion

    protected void btnBack_ServerClick(object sender, EventArgs e)
    {
        string url = "UserManager.aspx?IsReturn=true&table=" + tableCode;
        this.Page.Response.Redirect(url);
    }

    protected void btnSave_ServerClick(object sender, EventArgs e)
    {
        SavePageStateToDraft();
    }
    /// <summary>
    /// 判断是否所有必填的项都填写了
    /// </summary>
    /// <param name="values"></param>
    /// <param name="emptyType"></param>
    /// <returns></returns>
    private string CheckIsColNotNull(Dictionary<string, string> values, Dictionary<string, EnumHelper.E_EmptyType> emptyType)
    {
        if (values == null)
        {
            return null;
        }
        if (emptyType == null)
        {
            return null;
        }
        foreach (KeyValuePair<string, EnumHelper.E_EmptyType> kvp in emptyType)
        {
            if (kvp.Value == EnumHelper.E_EmptyType.CanNotBeNull)
            {
                if (!values.ContainsKey(kvp.Key.ToUpper()) || values[kvp.Key.ToUpper()] == "")
                {
                    return kvp.Key.ToUpper();
                }
            }

        }
        return null;
    }

    private string GetLoginUserIndexId()
    {        
        if (user == null)
        {
            Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='" + Request.ApplicationPath + "/Login.aspx';</script>");
            return null;
        }

        string skey = "IndexID-" + user.IndexID.ToString();
        return skey;
    }
}
